package Windows.Search;

import java.util.ArrayList;
import java.util.Random;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;

import Tools.IMG;
import Tools.InfoFormat;
import Tools.ToCenter;
import Tools.Units;
import Windows.PicPanel;
import XML.XMLNode;

/**
 * 模型效率严重底下，以后改成类似SQL试图表，用线程刷新（线程通信控制）----boolean
 * 
 * @author Administrator
 * 
 */
public class SearchTableModel extends AbstractTableModel {
	private class indexXF {
		XMLNode xf;
		final int index;
		int k;

		public indexXF(XMLNode xf, int index, int k) {
			super();
			this.xf = xf;
			this.index = index;
			this.k = k;
		}

	}
	public class toolColumn extends JPanel {
		private SearchTableModel stm;
		private JLabel jl;
		private XMLNode xn;

		public toolColumn(SearchTableModel stm, XMLNode xn) {
			this(xn);
			this.stm = stm;
			// UpdateICO();单元格渲染器自动条用
		}

		public toolColumn(XMLNode xn) {
			this.xn = xn;
			this.jl = new JLabel();
			this.add(jl);
			UpdateICO();
		}

		public JLabel getJl() {
			return jl;
		}

		public SearchTableModel getStm() {
			return stm;
		}

		public void setJl(JLabel jl) {
			this.jl = jl;
		}

		public void setStm(SearchTableModel stm) {
			this.stm = stm;
		}

		public void UpdateICO() {
			if (!xn.isLeafage()) {
				int pip = 0;
				try {
					pip = Integer.parseInt(xn.get("pip"));
				} catch (Exception e) {
				}
				jl.setText(pip <= 1 ? "" : isExpand(xn) ? "-" : "+");
				String str = xn.get("safety");
				int k = str == null ? 0 : Integer.parseInt(str);
				switch (k) {
				case 0:
					jl.setIcon(IMG.safety0);// 未知
					break;
				case 1:
					jl.setIcon(IMG.safety1);// 安全
					break;
				case 2:
					jl.setIcon(IMG.safety2);// 警告
					break;
				case 3:
					jl.setIcon(IMG.safety3);// 风险
					break;
				default:
					jl.setIcon(IMG.safety0);// 未知
				}
			}
		}

	}
	public class TreeTableValue {
		private SearchTableModel stm;
		final XMLNode xf;
		private Object value;

		public TreeTableValue(SearchTableModel stm, XMLNode xf, Object value) {
			super();
			this.stm = stm;
			this.xf = xf;
			this.value = value == null ? "" : value;
		}

		public SearchTableModel getStm() {
			return stm;
		}

		public Object getValue() {
			return value;
		}

		public XMLNode getXf() {
			return xf;
		}

		public void setStm(SearchTableModel stm) {
			this.stm = stm;
		}

		public void setValue(String value) {
			this.value = value;
		}

		@Override
		public String toString() {
			return value.toString();
		}
	}
	public static void main(String[] args) {
		JFrame jf = new JFrame();
		PicPanel pp = new PicPanel("Skin/resault/0.png");
		jf.setContentPane(pp);
		jf.setSize(200, 222);
		ToCenter.ToCenter(jf);
		jf.setVisible(true);
	}
	private String[] columnNames = { "安全", "资源名称", "类型", "评论", "资源大小", "更新日期", "速度", "资源数", "分享者", "MD5" };
	private ArrayList<XMLNode> al = new ArrayList<XMLNode>();
	private ArrayList<PicPanel> alii = new ArrayList<PicPanel>();

	private ArrayList<toolColumn> alToolColumn = new ArrayList<toolColumn>();

	private JTable table;

	private ArrayList<XMLNode> alDisplay = new ArrayList<XMLNode>();// 视图

	private int update = -1;

	int max = 1500;

	public SearchTableModel(JTable table) {
		this.table = table;
		table.setModel(this);

	}

	/**
	 * 添加一行数据
	 * 
	 * @param xf
	 */
	public void addRow(XMLNode xf) {
		if (xf == null) {
			System.out.print("搜索返回表格：XMLNode=NULL ");
			return;
		}
		setSuper(xf);// 设置主文件父节点，第一个到达的将成为主节点

		toolColumn tc = new toolColumn(this, xf);
		alToolColumn.add(tc);

		long time = Integer.parseInt(xf.get("speed"));
		time = time > max ? max : time < 1 ? 1 : time;
		// System.out.println("\tWidth:"+w+"/"+bitmp.getWidth()+"\tHeight:"+h+"/"+bitmp.getHeight()+"\tStart:"+j);
		double value = (double) time / max + new Random().nextFloat();
		// ImageIcon ii = new GuageImageIcon(bifg, bibg,
		// value).createImageIcon();
		PicPanel p = new PicPanel();
		p.setIexited(value < 0.2 ? IMG.image1 : value < 0.4 ? IMG.image2 : value < 0.6 ? IMG.image3 : value < 0.8 ? IMG.image4 : IMG.image5);
		alii.add(p);
		al.add(xf);
	}

	public void addRowList(Vector<XMLNode> xflist) {
		for (int i = 0; i < xflist.size(); i++) {
			XMLNode xf = xflist.get(i);
			addRow(xf);
		}
		update = -1;// 重新更新视图表

		// //////////////////////////////////////
		updateUI();
	}

	/**
	 * 展开/收缩
	 * 
	 * @param xf
	 */
	public void Expand(XMLNode xf) {
		if (!xf.isLeafage()) {
			String expand = xf.get("expand");
			Boolean b = !Boolean.valueOf(expand);
			xf.put("expand", b.toString());
			System.out.println("展开/收缩: Expand  >> " + xf);
			update = -1;// 重新建立视图
			updateUI();
		}
	}

	public ArrayList<XMLNode> getChild(XMLNode xf) {
		ArrayList<XMLNode> alxf = new ArrayList<XMLNode>();
		alxf.clear();
		for (int i = 0; i < al.size(); i++) {
			XMLNode xfs = al.get(i);
			if (xfs != null && xfs.getSUPER() == xf) {// 找到子节点
				if (xf != xfs)
					alxf.add(xfs);
			}
		}
		return alxf;
	}

	public ArrayList<XMLNode> getCoequality(XMLNode xf) {
		ArrayList<XMLNode> alxf = new ArrayList<XMLNode>();
		alxf.clear();
		for (int i = 0; i < al.size(); i++) {
			XMLNode xfs = al.get(i);
			if (xfs != null && xfs.getSUPER() == xf.getSUPER()) {// 找到子节点
				alxf.add(xfs);
			}
		}
		return alxf;
	}

	@Override
	public Class<TreeTableValue> getColumnClass(int Index) {
		// if(Index==0){
		// return toolColumn.class;
		// }else if(Index==6){
		// return ImageIcon.class;
		// }else
		return TreeTableValue.class;// 所有列以字符串类渲染
	}

	@Override
	public int getColumnCount() {
		return columnNames.length;
	}

	@Override
	public String getColumnName(int columnIndex) {
		return columnNames[columnIndex];
	}

	/**
	 * 取可视节点数量
	 * 
	 * @param xf
	 *            null表示所有根节点
	 * @return
	 */
	public int getExpandCount(XMLNode xf) {
		int count = 0;
		ArrayList<XMLNode> alxf = getChild(xf);// 取子节点
		for (int i = 0; i < alxf.size(); i++) {
			XMLNode xfs = alxf.get(i);
			count++;
			alDisplay.add(xfs);
			if (isExpand(xfs)) {
				count += getExpandCount(xfs);
			}
		}
		return count;
	}

	/**
	 * 
	 * @param xf
	 *            递归继承变量，没指针就这样吧
	 * @return
	 */
	private XMLNode getIndexXF(indexXF ixf) {
		ArrayList<XMLNode> alxf = getChild(ixf.xf);
		for (int i = 0; i < alxf.size(); i++) {
			XMLNode xfs = alxf.get(i);
			ixf.k++;
			if (ixf.k == ixf.index) {
				return xfs;
			} else if (isExpand(xfs)) {
				ixf.xf = xfs;
				xfs = getIndexXF(ixf);
				if (xfs != null)
					return xfs;
				else {
					// System.out.sy
				}
			}
		}
		return null;
	}

	public int getLayer(XMLNode xf) {
		// TODO Auto-generated method stub
		if (xf.getSUPER() == null)
			return 1;
		else
			return getLayer(xf.getSUPER()) + 1;
	}

	@Override
	public int getRowCount() {
		if (update == -1) {
			alDisplay.clear();
			update = getExpandCount(null);
		}
		return update;
	}

	public XMLNode getSuperOnlyNode(XMLNode xf) {
		return getSuperOnlyNode(xf, "md5");
	}

	/**
	 * 判断是否存在这个文件
	 * 
	 * @param xf
	 * @param onlyFlag
	 *            保正唯一的列
	 * @return 找到的的节点
	 */
	public XMLNode getSuperOnlyNode(XMLNode xf, String onlyFlag) {
		if (xf == null) {
			return null;
		}
		XMLNode xfs = null;
		for (int i = 0; i < al.size(); i++) {
			xfs = al.get(i);
			String value = xfs.get(onlyFlag);
			String value2 = xf.get(onlyFlag);
			if (value != null && value2 != null && value.equals(value2))
				return xfs;
		}
		// System.out.println("getSuperOnlyNode:"+xfs);
		return null;
	}

	@Override
	public Object getValueAt(int row, int column) {
		XMLNode xf = getXmlFlag(row);
		if (xf == null) {
			System.out.println("取无效索引！" + row + "/" + column);
			return null;
		}
		boolean leaf = xf.isLeafage();
		switch (column) {
		case 0:
			return new TreeTableValue(this, xf, alToolColumn.get(al.indexOf(xf)));// alToolColumn.get(row);
		case 1:
			return new TreeTableValue(this, xf, xf.get("name"));
		case 2:
			String str = xf.get("name");
			return new TreeTableValue(this, xf, leaf ? "" : InfoFormat.FileTypeBewrite(InfoFormat.getTypeStr(str)));
		case 3:
			return new TreeTableValue(this, xf, leaf ? "" : "(256)");
		case 4:
			return new TreeTableValue(this, xf, leaf ? "" : Units.byteCondense(Long.valueOf(xf.get("size"))));
		case 5:
			return new TreeTableValue(this, xf, leaf ? "" : InfoFormat.formatTime(Long.valueOf(xf.get("time"))));
		case 6:

			return new TreeTableValue(this, xf, alii.get(al.indexOf(xf)));
		case 7:
			return new TreeTableValue(this, xf, leaf ? "" : xf.get("pip"));
		case 8:
			return new TreeTableValue(this, xf, xf.get("userid"));
		case 9:
			return new TreeTableValue(this, xf, leaf ? "" : xf.get("md5"));
		default:
			return "";
		}

	}

	public XMLNode getXmlFlag(int index) {
		if (index < alDisplay.size()) {
			return alDisplay.get(index);
		}
		System.out.println("[取行数据]越界纠正!");
		XMLNode xf = getIndexXF(new indexXF(null, index, -1));
		return xf;
	}

	@Override
	public boolean isCellEditable(int rowIndex, int columnIndex) {
		return false;// 不可编辑
	}

	public boolean isExpand(XMLNode xf) {
		boolean expand = false;// 是否展开
		String bool = xf.get("expand");
		try {
			expand = Boolean.valueOf(bool);
		} catch (Exception e) {
		}
		return expand;
	}

	public void removeRow(int row) {
		al.remove(getXmlFlag(row));// 未删除下节点
		updateUI();
	}

	/**
	 * 行xml设置
	 * 
	 * @param xf
	 */
	private void setSuper(XMLNode xf) {
		xf.setSUPER(null);// 预设
		xf.setLeafage(true); // 保证叶节点
		XMLNode xfs = getSuperOnlyNode(xf);

		if (xfs != null && xfs != xf) {
			xf.setSUPER(xfs);
			int i = 0;
			try {
				i = Integer.parseInt(xfs.get("pip"));
			} catch (Exception e) {
			}
			i++;
			xfs.put("pip", String.valueOf(i));

		} else {
			xf.setLeafage(false);
			xf.put("expand", "false");
			xf.put("pip", "1");
		}
	}

	/**
	 * 刷新TableUI
	 */
	public void updateUI() {
		java.awt.EventQueue.invokeLater(new Runnable() {
			@Override
			public void run() {
				table.updateUI();
			}
		});
	}

}
